package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"manuscriptservice/manuscriptservicerpc/internal/svc"
	"manuscriptservice/manuscriptservicerpc/manuscriptservicerpc"
	"manuscriptservice/model/cache"
	"manuscriptservice/model/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *manuscriptservicerpc.ListRequest) (*manuscriptservicerpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	var List []*manuscriptservicerpc.ManuList

	key := fmt.Sprintf("ManuList_%s", in)

	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	if result == "" {
		List = mysql.ManuList(mysql.DB, List, in)
		marshal, _ := json.Marshal(List)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*120)
	} else {
		json.Unmarshal([]byte(result), &List)
	}

	return &manuscriptservicerpc.ListResponse{
		List: List,
	}, nil
}
